package com.pearadmin.pro.modules.weixin;

import com.pearadmin.pro.common.tools.core.OkHttpUtils;
import com.pearadmin.pro.modules.weixin.service.WeiChatCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/weiCallBack")
@Slf4j
public class WeiChatCallbackController {

    @Autowired
    private WeiChatCallbackService weiChatCallbackService;


    //第一次get请求验证
    @GetMapping(value = "/callBack")
    public void verifyURL(String msg_signature, String timestamp, String nonce, String echostr, HttpServletResponse response) {
        // 验证URL成功，将sEchoStr返回
        String data = weiChatCallbackService.verifyURL(msg_signature,timestamp,nonce,echostr);
        try {
            OkHttpUtils.write(response,data);
            log.info("企业微信验证数据成功：{}",data);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("企业微信验证数据失败");
        }
    }

    //接受post请求消息推送
    @PostMapping("/callBack")
    @ResponseBody
    public void callBack(HttpServletRequest request, String msg_signature, String timestamp, String nonce)  {
        weiChatCallbackService.doCallBack(request, msg_signature, timestamp, nonce);
    }

}
